//
//  OfficeRepireViewController.swift
//  EduManage
//
//  Created by design02 on 16/12/12.
//  Copyright © 2016年 wsl. All rights reserved.
//

import UIKit

class OfficeRepireViewController: BaseViewController, UITableViewDelegate, UITableViewDataSource {

    var segmentedControl = UISegmentedControl()
    var switchSegment = UISegmentedControl()
    var tableView = UITableView()
    
    var mark = "1"
    
    var workArray = NSMutableArray()
    var classArray = NSMutableArray()
    var teacherArray = NSMutableArray()
    
    
    let top = 10
    var pageIndex = 1
    
    var modetype: String!
    
    var chart = PDChart()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.title = "在线报修"
        
        setupViews()
    }
    
    func setupViews(){
        
        let array = ["统计汇总","按用户","按分类"]
        segmentedControl = UISegmentedControl.init(items: array)
        segmentedControl.frame = CGRect(x: 15, y: 74, width: screenW - 30, height: 40)
        segmentedControl.selectedSegmentIndex = 0
        segmentedControl.tintColor = barColor
        segmentedControl.addTarget(self, action: #selector(ClassWorkViewController.selTab), for: UIControlEvents.valueChanged)
        self.view.addSubview(segmentedControl)
        
        
        tableView = UITableView.init(frame: CGRect(x: 0, y: segmentedControl.frame.maxY + 10, width: screenW, height: screenH - segmentedControl.frame.maxY - 10))
        tableView.backgroundColor = UIColor.init(hexString: "f6f6f6", alpha: 1)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = UITableViewCellSeparatorStyle.none
        self.view.addSubview(tableView)
        setupRefresh()
        
    }
    func setupRefresh() {
        if mark == "1" {
            tableView.header = MJRefreshNormalHeader.init(refreshingTarget: self, refreshingAction: #selector(OfficeRepireViewController.refresh))

            tableView.footer = nil
            self.tableView.header.beginRefreshing()
        }else if mark == "2" {
            tableView.header = MJRefreshNormalHeader.init(refreshingTarget: self, refreshingAction: #selector(OfficeRepireViewController.refresh))
            tableView.footer = MJRefreshAutoNormalFooter.init(refreshingTarget: self, refreshingAction: #selector(OfficeRepireViewController.loadMore))
            
            self.tableView.header.beginRefreshing()
        }else {
            tableView.header = MJRefreshNormalHeader.init(refreshingTarget: self, refreshingAction: #selector(OfficeRepireViewController.refresh))
            
            tableView.footer = nil
            self.tableView.header.beginRefreshing()
        }
        
    }
    func loadMore() {
        if (reachability?.isReachable())! {
            let user = getUserPojo()
            let url = server + adminofficewebappapi
            pageIndex += 1
            let page: String = String(pageIndex)
            
            
            let request = requestHeader + "6</t><schid>" + user.schid + "</schid><top>12</top><pageindex>" + page + "</pageindex></channel></rss>"
            workArray = getData(url, request: request)
            
            tableView.reloadData()
        } else {
            let alert = UIAlertView.init(title: "错误提示", message: "似乎已断开与互联网的连接", delegate: nil, cancelButtonTitle: "知道了")
            alert.show()
            self.perform(#selector(OfficeRepireViewController.dimissAlert(alert:)), with: alert, afterDelay: 2.0)
            
            HYLog("网络连接：不可用")
        }

        tableView.footer.endRefreshing()
        
    }
    
    func dimissAlert(alert: UIAlertView) {
        alert.dismiss(withClickedButtonIndex: alert.cancelButtonIndex, animated: true)
    }
    
    /**
     刷新数据
     */
    func refresh() {
        
        if (reachability?.isReachable())! {
            
            let user = getUserPojo()
            let url = server + adminofficewebappapi
            
            if mark == "1" {
                /**
                 - 统计发布数量接口地址：GJ_ModularmentBG.ashx?t=5
                 
                 2）统计发布数量参数：
                 XmlNode schidxml = ndoc.SelectSingleNode("//rss/channel/schid");
                 */
                
                let request = requestHeader + "5</t><schid>" + user.schid + "</schid></channel></rss>"
                
                workArray = getData(url, request: request)
                
                tableView.separatorStyle = UITableViewCellSeparatorStyle.none
                
                setupSwitchBtn()
                
                if switchSegment.selectedSegmentIndex == 0 {
                    
                    self.chart.removeFromSuperview()
                    
                    if !self.tableView.subviews.contains(chart) {
                        
                        let barChart: PDBarChart = OfficeLeaveViewController().getBarChart(workArray)
                        chart = barChart
                        self.tableView.addSubview(chart)
                    }
                    
                    chart.strokeChart()
                    
                }else if switchSegment.selectedSegmentIndex == 1 {
                    self.chart.removeFromSuperview()
                    
                    if !self.tableView.subviews.contains(chart) {
                        
                        let barChart: PDLineChart = OfficeLeaveViewController().getLineChart(workArray)
                        chart = barChart
                        self.tableView.addSubview(chart)
                    }
                    
                    chart.strokeChart()
                    
                    print("显示折线图")
                }
                
                
                
            }else if mark == "2" {
                
                self.chart.removeFromSuperview()
                self.switchSegment.removeFromSuperview()
                
                /**
                 3）报修（按用户）接口地址：GJ_ModularmentBG.ashx?t=6
                 4）报修（按用户）参数：
                 
                 XmlNode schidxml = ndoc.SelectSingleNode("//rss/channel/schid");
                 XmlNode topxml = ndoc.SelectSingleNode("//rss/channel/top");
                 XmlNode pageindexxml = ndoc.SelectSingleNode("//rss/channel/pageindex");
                 */
                pageIndex = 1
                let page: String = String(pageIndex)
                let request = requestHeader + "6</t><schid>" + user.schid + "</schid><top>12</top><pageindex>" + page + "</pageindex></channel></rss>"
                
                classArray = getData(url, request: request)
                tableView.separatorStyle = UITableViewCellSeparatorStyle.singleLine
                
                if classArray.count == 0 {
                    TSMessage.showNotification(in: self, title: "温馨提示", subtitle: "暂时还没有在线报修信息、请添加后重试！", image: nil, type: TSMessageNotificationType.warning, duration: 2.0, callback: nil, buttonTitle: "知道了", buttonCallback: nil, at: TSMessageNotificationPosition.top, canBeDismissedByUser: true)
                }
                
            }else if mark == "3" {
                
                self.chart.removeFromSuperview()
                self.switchSegment.removeFromSuperview()
                /**
                 - 报修（按分类）接口地址：GJ_ModularmentBG.ashx?t=7
                 - 报修（按分类）参数：
                 
                 XmlNode schidxml = ndoc.SelectSingleNode("//rss/channel/schid");
                 
                 //考虑到按分类的话 种类不是太多、所以直接列表全部
                 XmlNode topxml = ndoc.SelectSingleNode("//rss/channel/top");
                 XmlNode pageindexxml = ndoc.SelectSingleNode("//rss/channel/pageindex");
                 */
                pageIndex = 1
                let page: String = String(pageIndex)
                let request = requestHeader + "7</t><schid>" + user.schid + "</schid></channel></rss>"
                
                
                teacherArray = getData(url, request: request)
                tableView.separatorStyle = UITableViewCellSeparatorStyle.singleLine
                
                if teacherArray.count == 0 {
                    TSMessage.showNotification(in: self, title: "温馨提示", subtitle: "暂时还没有在线报修信息、请添加后重试！", image: nil, type: TSMessageNotificationType.warning, duration: 2.0, callback: nil, buttonTitle: "知道了", buttonCallback: nil, at: TSMessageNotificationPosition.top, canBeDismissedByUser: true)
                }
                
            }
            
            tableView.reloadData()
            
        } else {
            HYLog("网络连接：不可用")
        }
        
        
        tableView.header.endRefreshing()
    }
    /**
     选项切换
     */
    func selTab() {
        let n = segmentedControl.selectedSegmentIndex
        switch n {
        case 0:
            mark = "1"
            setupRefresh()
            break
        case 1:
            mark = "2"
            setupRefresh()
            break
        case 2:
            mark = "3"
            setupRefresh()
            break
        default:
            break
        }
    }
    
    /**
     高度
     
     - parameter tableView: tableview
     - parameter indexPath: item
     
     - returns: 高度
     */
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if mark == "1" {
            return 0
        }else {
            return 60
        }
    }
    /**
     多少行
     
     - parameter tableView: tableview
     - parameter section:
     
     - returns: 行数
     */
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        if mark == "1" {
            return 0
        }else if mark == "2" {
            return classArray.count
        }else if mark == "3" {
            return teacherArray.count
        }else {
            return 0
        }
        
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if mark == "1" {
            let cellIdentifier = "ClassSendTableViewCellIdentifier";
            
            let cell: UITableViewCell = UITableViewCell.init(style: UITableViewCellStyle.default, reuseIdentifier: cellIdentifier)
            cell.selectionStyle = UITableViewCellSelectionStyle.none;
            if (indexPath as NSIndexPath).row < workArray.count {
                
                let dic = workArray[indexPath.row] as! JSON
                let mMonth = dic["mMonth"].stringValue
                let csnum = dic["csnum"].stringValue
                let StartDate = dic["StartDate"].stringValue
                let EndDate = dic["EndDate"].stringValue
                
                print("\(mMonth)月份、\(csnum)发布、\(StartDate.components(separatedBy: " ").first!)-\(EndDate.components(separatedBy: " ").first!)")
                
            }
            
            return cell
            
        }else if mark == "2" {
            let cellIdentifier = "ClassSendTableViewCellIdentifier";
            
            let cell: OfficeLeaveTableViewCell = OfficeLeaveTableViewCell.init(style: UITableViewCellStyle.default, reuseIdentifier: cellIdentifier)
            cell.selectionStyle = UITableViewCellSelectionStyle.none;
            if (indexPath as NSIndexPath).row < classArray.count {
                
                let dic = classArray[indexPath.row] as! JSON
                let teaname = dic["teaname"].stringValue
                //保修次数
                let csnum = dic["csnum"].stringValue
                // 排列顺序
                let cs = dic["cs"].stringValue
                
                var photo = dic["photo"].stringValue
                photo = photo.replacingOccurrences(of: "../..", with: "").replacingOccurrences(of: "../", with: "/view/")
                photo = server + photo
                cell.userTx.sd_setImage(with: URL.init(string: photo), placeholderImage: UIImage.init(named: "touxiangm"))
                
                cell.userName.text = teaname
                cell.countLabel.text = "报修次数: \(csnum)"
                
            }
            
            return cell
            
        }else {
            let cellIdentifier = "ClassCountTableViewCellIdentifier";
            
            let cell: Office2LabelTableViewCell = Office2LabelTableViewCell.init(style: UITableViewCellStyle.default, reuseIdentifier: cellIdentifier)
            cell.selectionStyle = UITableViewCellSelectionStyle.none;
            if (indexPath as NSIndexPath).row < teacherArray.count {
                let dic = teacherArray[indexPath.row] as! JSON
                let cs = dic["cs"].stringValue
                let csnum = dic["csnum"].stringValue
                let codename = dic["codename"].stringValue
                let codeid = dic["codeid"].stringValue
                let codetype = dic["codetype"].stringValue
                
                print("在线保修-按分类-排名:\(cs)、数量:\(csnum)、分类名称:\(codename)、\(codeid)、\(codetype)")
                
//                cell.userTx.image = UIImage.init(named: "touxiangm")
//                cell.userName.text = codename
//                cell.unReadLabel.text = "数量: \(csnum)        "
                cell.firstLabel.text = codename
                cell.secondLabel.text = "数量: \(csnum)"
            }
            
            return cell
            
        }
        
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
    }
    
    //MARK: - 设计图表
    
    func getBarChart() -> PDBarChart {
        
        
        let tempArr = NSMutableArray()
        var tempPointArr: [CGPoint]?
        var tempMouthArr: [String]?
        
        tempPointArr = [CGPoint]()
        tempMouthArr = [String]()
        
        for i in 0...workArray.count-1 {
            let tempNumber = (workArray[i] as! JSON)["csnum"].intValue
            let temgmMonth = (workArray[i] as! JSON)["mMonth"].intValue
            let tempPoint:CGPoint = CGPoint(x: (workArray[i] as! JSON)["mMonth"].intValue, y: (workArray[i] as! JSON)["csnum"].intValue)
            
            tempArr.add(tempNumber)
            tempPointArr?.append(tempPoint)
            tempMouthArr?.append("\(temgmMonth)月")
            
        }
        
        let dataItem: PDBarChartDataItem = PDBarChartDataItem()
        
        let m = tempArr.value(forKeyPath: "@max.intValue")! as! Int
        var ymax = CGFloat(0.0)
        var yinterval = CGFloat(0.0)
        
        if (m < 10) {
            ymax = CGFloat((m+1)*10)
            yinterval = 1.0
            
        }else if (m > 10 && m < 100) {
            ymax = CGFloat((m/10+1)*10)
            yinterval = 10.0
            
        }else if (m > 100 && m < 1000) {
            ymax = CGFloat((m/100+1)*10)
            yinterval = 100.0
            
        }else {
            ymax = CGFloat((m/1000+1)*10)
            yinterval = 1000.0
        }
        
        
        
        dataItem.xMax = CGFloat((tempMouthArr?.count)!)
        dataItem.xInterval = 1.0
        dataItem.yMax = ymax
        dataItem.yInterval = yinterval
        dataItem.barPointArray = tempPointArr
        //            [CGPoint(x: 1.0, y: 95.0), CGPoint(x: 2.0, y: 25.0), CGPoint(x: 3.0, y: 30.0), CGPoint(x: 4.0, y:50.0), CGPoint(x: 5.0, y: 55.0), CGPoint(x: 6.0, y: 60.0), CGPoint(x: 7.0, y: 95.0), CGPoint(x: 8.0, y: 25.0), CGPoint(x: 9.0, y: 30.0), CGPoint(x: 10.0, y:50.0), CGPoint(x: 11.0, y: 55.0), CGPoint(x: 12.0, y: 60.0)]
        dataItem.xAxesDegreeTexts = tempMouthArr
        //            ["八月", "九月", "十月", "十一月", "十二月", "一月", "九月", "十月", "十一月", "十二月", "一月", "二月"]
        dataItem.yAxesDegreeTexts = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]
        
        let frameW = self.view.frame.size.width
        let barChart: PDBarChart = PDBarChart(frame: CGRect(x: 0, y: 0, width: frameW, height: frameW), dataItem: dataItem)
        return barChart
    }
   
    func setupSwitchBtn() {
        
        if !self.tableView.subviews.contains(switchSegment) {
            
            switchSegment = UISegmentedControl.init(items: ["柱状图","折线图"])
            switchSegment.frame = CGRect(x: (screenW-150)/2, y: 5, width: 150, height: 30)
            switchSegment.selectedSegmentIndex = 0
            switchSegment.tintColor = UIColor.init(hexString: "#666666", alpha: 1.0)
            switchSegment.addTarget(self, action: #selector(OfficeRepireViewController.refresh), for: UIControlEvents.valueChanged)
            self.tableView.addSubview(switchSegment)
        }
        
    }

    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
